package CmdHandle;

import javafx.concurrent.Task;
import javafx.scene.text.Text;
import utils.CommandDefault;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;

public class HandleCommand extends Task<Integer> {
    private final String mCmd;
    private Text mText;
    private int mProcessValue=0;

    public HandleCommand(String mCmd,Text mText,int processValue) {
        this.mCmd = mCmd;
        this.mText=mText;
        this.mProcessValue=processValue;
    }
    //每一个命令一个进度条，所以传入的进度条默认为 0
    public HandleCommand(String mCmd, Text mText) {
        this.mCmd = mCmd;
        this.mText = mText;
    }

    @Override
    protected void updateMessage(String message) {
        super.updateMessage(message);
        mText.setText(message);
    }

    //命令行操作
    private void commandHandle(String cmd) {
        System.out.println(cmd);
        Runtime run = Runtime.getRuntime();
        Process p = null;
        //准备工作完成
        updateProgress(mProcessValue+20, CommandDefault.MAX_PROGRESS);
        try {
            p = run.exec(cmd);
            //开始运行命令
            updateProgress(mProcessValue+40,CommandDefault.MAX_PROGRESS);
            InputStreamReader inputStreamReader = new InputStreamReader(p.getInputStream(), StandardCharsets.UTF_8);
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String line;
            String content = "";
            //临时进度值
            int temp=0;
            //获取命令行输出的结果
            while ((line = bufferedReader.readLine()) != null) {
                content += line + "\n";
                if(temp<=80){
                    temp+=5;
                }
                updateProgress(mProcessValue+temp,CommandDefault.MAX_PROGRESS);
            }
            updateProgress(mProcessValue+85,CommandDefault.MAX_PROGRESS);
            System.out.println(content);
            updateMessage(content);
            updateProgress(mProcessValue+100,CommandDefault.MAX_PROGRESS);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //返回进度条的值
    @Override
    protected Integer call() throws Exception {
        System.out.println("开始执行："+mCmd);
        commandHandle(mCmd);
        System.out.println("执行完成："+mCmd);
        return null;
    }

    @Override
    protected void updateProgress(long workDone, long max) {
        super.updateProgress(workDone, max);
    }


}
